<template>
	<view class="main">
		<u-form :model="form" ref="uForm">
			<u-form-item label="头像">
				<u-avatar :src="form.avatarUrl" @click="upImage"></u-avatar>
			</u-form-item>
			<u-form-item label="姓名">
				<u-input v-model="form.nickName" />
			</u-form-item>
			<u-form-item label="性别">
				<u-input v-model="form.gender" type="select" @click='show=true' />
				<u-action-sheet :list="list" v-model="show" @click="select"></u-action-sheet>
			</u-form-item>
			<u-form-item label="简介">
				<u-input type="textarea" v-model="form.intro" />
			</u-form-item>
			<view class="button">
				<u-button shape="circle" @click="upload">上传</u-button>
			</view>
		</u-form>
	</view>
</template>

<script>
	const db = wx.cloud.database()
	export default {
		data() {
			return {
				form: {
					nickName: '',
					avatarUrl: '',
					gender: '',
					intro: '',
					barrage: ''
				},
				list: [{
					text: '女',
					id: 0
				}, {
					text: '男',
					id: 1
				}, {
					text: '不显示',
					id: 2
				}],
				show: false,
				id:null
			}
		},
		onLoad() {
			uni.showLoading({
				title:'获取中…'
			})
			db.collection('user-list').get({
				success: res => {
					console.log("res",res.data[0]);
					const data = res.data[0]
					let sex = '男'
					if(data.gender == 0 || data.gender == '女') sex = '女'
					this.id = data._id
					this.form = {
						intro: data.intro? data.intro:'',
						barrage: true,
						gender: sex,
						nickName: data.nickName,
						avatarUrl: data.avatarUrl
					}
					uni.hideLoading()
				},
				fail: err => console.log("seting onloud错误", err)
			})
		},
		methods: {
			async upload() {
				uni.showLoading({
					title:'正在上传'
				})
				if(this.id===null){return this.$u.toast('错误')}
				const data = {...this.form}
				await db.collection('user-list').doc(this.id).update({
					data
				}).catch(err=>console.log("upload 错误",err))
				await db.collection('user-list').doc(this.id).get().then(res=>{
					uni.setStorageSync('login',res.data)
					console.log('res',res.data);
					this.$u.toast('上传成功')
				}).catch(err=>console.log("upload 错误",err))
			},
			barrage(e) {
				this.form.barrage = e.detail.value
			},
			select(e) {
				this.form.gender = this.list[e].text
			},
			upImage(e) {
				uni.chooseImage({
					count: 1,
					success: res => {
						uni.showLoading({
							title:'上传中…',
						})
						const name = new Date().getTime()
						wx.cloud.uploadFile({
							cloudPath: `avatar/${name}.png`,
							filePath: res.tempFilePaths[0],
							success: res => {
								this.form.avatarUrl = res.fileID
								this.$u.toast('上传成功')
							},
							fail: err => console.log("upload 错误",err)
						})
					}
				})
			}
		}
	}
</script>

<style scoped>
	.main {
		width: 710rpx;
		padding: 20rpx;
	}

	.button {
		width: 510rpx;
		margin: 50rpx 100rpx;
	}
</style>
